<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 员工列表
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select v-model="query.status"
                   placeholder="雇佣状态"
                   clearable
                   size="medium"
                   class="handle-select mr10">
          <el-option v-for="(item, index) in staffStatus"
                     :key="index"
                     :value="item.value"
                     :label="item.label"></el-option>
        </el-select>
        <el-select v-model="query.department_id"
                   placeholder="所在部门"
                   clearable
                   size="medium"
                   class="handle-select mr10">
          <el-option v-for="(item, index) in allDepartments"
                     :key="index"
                     :value="item.id"
                     :label="item.name_path"></el-option>
        </el-select>
        <el-input v-model="query.name"
                  placeholder="姓名"
                  clearable
                  size="medium"
                  class="handle-input mr10"></el-input>
        <el-input v-model="query.job_no"
                  placeholder="工号"
                  clearable
                  size="medium"
                  class="handle-input mr10"></el-input>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="medium"
                   @click="handleSearch">搜索</el-button>
        <el-button type="primary"
                   icon="el-icon-download"
                   size="medium"
                   style="float: right"
                   @click="exportExcel">导出</el-button>
        <el-button type="primary"
                   icon="el-icon-document-add"
                   size="medium"
                   style="float: right"
                   @click="handleAdd">添加</el-button>
      </div>
      <el-table :data="tableData"
                border
                size="medium"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header">
        <el-table-column prop="id"
                         label="ID"
                         width="60"
                         align="left"></el-table-column>
        <el-table-column prop="name"
                         label="姓名"></el-table-column>
        <el-table-column prop="job_no"
                         min-width="80"
                         label="工号"></el-table-column>
        <el-table-column prop="department.name_path"
                         min-width="140"
                         label="所在部门"></el-table-column>
        <el-table-column prop="leader.name"
                         label="上级"></el-table-column>
        <el-table-column prop="company_name"
                         min-width="140"
                         label="法人主体"></el-table-column>
        <el-table-column prop="entry_date"
                         label="入职日期"></el-table-column>
        <el-table-column label="雇佣状态"
                         align="left">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '在职'"
                    type="success">{{ scope.row.status }}</el-tag>
            <el-tag v-if="scope.row.status === '离职中'"
                    type="warning">{{ scope.row.status }}</el-tag>
            <el-tag v-if="scope.row.status === '离职'"
                    type="danger">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="left_date"
                         label="离职日期"></el-table-column>

        <el-table-column prop="created_at"
                         label="创建时间"></el-table-column>
        <el-table-column label="操作"
                         min-width="140"
                         align="left">
          <template #default="scope">
            <el-button type="text"
                       icon="el-icon-edit"
                       v-if="scope.row.status != '封存'"
                       @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button type="text"
                       icon="el-icon-delete"
                       class="red"
                       @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       layout="total, prev, pager, next"
                       :current-page="query.pageIndex"
                       :page-size="query.pageSize"
                       :total="pageTotal"
                       @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="title"
               v-model="editVisible"
               width="40%">
      <el-form ref="formRef"
               :rules="rules"
               :model="form"
               label-width="80px">
        <el-form-item label="姓名"
                      prop="name">
          <el-input v-model="form.name" placeholder="请输入"
                    style="width:50%"></el-input>
        </el-form-item>
         <el-form-item label="所在部门"
                      prop="department_id">
          <el-select v-model="form.department_id"
                     placeholder="请选择">
            <el-option v-for="(item, index) in allDepartments"
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级"
                      prop="leader_id">
          <el-select v-model="form.leader_id"
                     placeholder="请选择">
            <el-option v-for="(item, index) in allStaffs"
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="法人主体"
                      prop="company_id">
          <el-select v-model="form.company_id"
                     placeholder="请选择">
            <el-option v-for="(item, index) in allCompany"
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary"
                     v-if="form.id > 0"
                     @click="saveEdit">确 定</el-button>
          <el-button type="primary"
                     v-if="form.id == 0"
                     @click="saveAdd">添 加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  staffList,
  staffAll,
  departmentAll,
  companyAll,
  updateStaff,
  addDepartment,
  deleteStaff,
  exportDepartment,
} from "../../api/index";

export default {
  name: "staff_list",
  setup() {
    const query = reactive({
      name: "",
      job_no: "",
      department_id: "",
      leader_id: "",
      status: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const tableData = ref([]);
    const pageTotal = ref(0);
    // 获取表格数据
    const getData = () => {
      staffList(query).then((res) => {
        tableData.value = res.data.data;
        pageTotal.value = res.data.total || 10;
      });
    };
    getData();

    // 雇佣状态
    const staffStatus = ref([
      {
        value: '在职',
        label: '在职'
      }, {
        value: '离职中',
        label: '离职中'
      }, {
        value: '离职',
        label: '离职'
      },
    ])

    // 查询操作
    const handleSearch = () => {
      query.pageIndex = 1;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.pageIndex = val;
      getData();
    };

    // 页面初始化，渲染完dom后获取初始数据绑定到dom上
    onMounted(() => {
      getStaffs();
      getCompanies();
    });

    // 获取员工列表
    const allStaffs = ref([])
    const getStaffs = () => {
      staffAll().then((res) => {
        if (res.code == 0) {
          // 赋值
          allStaffs.value = res.data
          return
        }
        allStaffs.value = []
      });
    };

    // 获取所有部门
    const allDepartments = ref([])
    const getDepartments = () => {
      departmentAll().then((res) => {
        if (res.code == 0) {
          // 给组件赋值
          allDepartments.value = res.data
        } else {
          allDepartments.value = []
        }
      })
    }

    // 获取所有生效的法人主体
    const allCompany = ref([])
    const getCompanies = () => {
      companyAll().then((res) => {
        if (res.code == 0) {
          allCompany.value = res.data
        } else {
          allCompany.value = []
        }
      })
    }

    // 删除操作
    const handleDelete = (row) => {
      // 二次确认删除
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          let params = {
            id: row.id,
          }
          deleteStaff(params).then((res) => {
            if (res.code == 0) {
              editVisible.value = false
              handleSearch()
              ElMessage.success("删除成功！");
            } else {
              ElMessage.error(res.msg)
            }
          })
        })
        .catch(() => {
          ElMessage.success("取消")
        });
    };

    // 表格编辑时弹窗和保存
    const editVisible = ref(false);
    let form = reactive({
      id: 0,
      name: "",
      job_no: "",
      department_id: "",
      leader_id: "",
      company_id: "",
    });
    // 编辑
    let idx = -1;
    const title = ref("");
    const handleEdit = (index, row) => {
      // console.log(row)
      idx = index;
      // 重新请求组件中的数据
      getCompanies()
      Object.keys(form).forEach((item) => {
        form[item] = row[item];
      });
      title.value = "编辑员工"
      editVisible.value = true;
    };

    // 新增
    const handleAdd = () => {
      getStaffs()
      getCompanies()
      // 清空form直接信息
      resetForm()
      title.value = "添加员工"
      editVisible.value = true;
    }

    // 表单规则
    const rules = {
      name: [
        { required: true, message: "请输入姓名", trigger: "blur" },
      ],
      department_id: [
        { required: true, message: "请选择所在部门", trigger: "blur" },
      ],
      leader_id: [
        { required: true, message: "请选择上级", trigger: "blur" },
      ],
    };
    const formRef = ref(null);

    // 提交更新员工
    const saveEdit = () => {
      // 表单校验
      formRef.value.validate((valid) => {
        if (valid) {
          updateStaff(form).then((res) => {
            if (res.code == 0) {
              editVisible.value = false
              handleSearch()
              ElMessage.success("更新成功！");
            } else {
              ElMessage.error(res.msg)
            }
          })
        } else {
          return false;
        }
      });
    };

    // 提交新增员工
    const saveAdd = () => {
      // 表单校验
      formRef.value.validate((valid) => {
        if (valid) {
          console.log(form)
          addDepartment(form).then((res) => {
            if (res.code == 0) {
              editVisible.value = false
              handleSearch()
              ElMessage.success("添加成功！");
            } else {
              ElMessage.error(res.msg)
            }
          })
        } else {
          return false;
        }
      });
    };

    // 导出excel
    const exportExcel = () => {
      exportDepartment(query).then((res) => {
        if (res.code == 0) {
          editVisible.value = false
          ElMessage.success("成功！");

          // 下载文件，原理：拼接url，后端接收到get请求，返回文件信息，实现导出功能
          const a = document.createElement('a')
          a.href = "/api/download?file_path=" + res.data.file_path + "&file_name=" + res.data.file_name
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click() // 点击下载
          document.body.removeChild(a) // 下载完成移除元素
        } else {
          ElMessage.error(res.msg)
        }
      })
    };

    // 清空
    const resetForm = function () {
      form["id"] = 0
      form["name"] = ""
      form["parent_id"] = ""
      form["leader_id"] = ""
      form["status"] = ""
      form["company_id"] = ""
    }

    return {
      query,
      tableData,
      pageTotal,
      editVisible,
      form,
      formRef,
      rules,
      allStaffs,
      allDepartments,
      allCompany,
      handleSearch,
      handlePageChange,
      handleDelete,
      handleEdit,
      handleAdd,
      saveEdit,
      saveAdd,
      title,
      staffStatus,
      exportExcel,
    };
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.green {
  color: #67c23a;
}
.yellow {
  color: #e6a23c;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
